# encoding: utf-8
# @File  : zhihu.py
# @Author: Ac
# @Date  : 2024/12/03/23:31
# @Note  : 搜集知乎文章
import time
import requests
import scrapy
import re
import cv2

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from matplotlib import pyplot as plt


class ZhihuSpider(scrapy.Spider):
    """
    知乎爬虫
    """
    name = 'zhihu2'
    allowed_domains = ['www.zhihu.com']
    start_urls = ['https://www.zhihu.com/']

    @classmethod
    def start_requests(self):
        """
        div[class='SignFlow-tab']
        spider：init
        :return:
        """

        chrome_options = Options()
        # chrome_options.add_argument('--headless')  # 无界面模式
        chrome_options.add_argument('--window-size=1920,1080')  # 设置框大小，避免无头模式识别不出按钮
        chrome_options.add_argument('--disable-gpu')  # 禁用显卡
        chrome_options.add_argument('--incognito')  # 隐私模式
        chrome_options.add_argument("--user-agent={}".format(
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.11"))  # 替换UA
        chrome_options.add_argument(
            "--disable-blink-features=AutomationControlled")  # 从 Chrome 88 开始，它的 V8 引擎升级了，加了这个参数，window.navigator.webdriver=false

        # 不显示上方的 Chrome正在受到自动化测试软件的控制
        chrome_options.add_experimental_option('useAutomationExtension', False)
        chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])

        driver = webdriver.Chrome(executable_path="ArticleSpider/drivers/chromedriver", options=chrome_options)

        # 打开知乎登录页面
        driver.get('https://www.zhihu.com/signin')

        # 切换密码登录
        driver.find_element_by_css_selector('.SignFlow-tabs div:last-child').click()

        # 账号输入框
        # input[placeholder='手机号或邮箱']
        username = "18438548185"
        password = "gzx0813.bfg"

        driver.find_element_by_css_selector(
            "input[placeholder='手机号或邮箱']").send_keys(
            username)
        driver.implicitly_wait(2)  # 隐式等待5秒

        driver.find_element_by_css_selector(
            "input[placeholder='密码']").send_keys(
            password)
        driver.implicitly_wait(2)  # 隐式等待5秒

        # 登录按钮
        driver.find_element_by_css_selector(
            "button[type='submit']").click()

        # driver.implicitly_wait(5)  # 隐式等待5秒
        time.sleep(5)
        # element = driver.find_element(By.XPATH, "//div[@id='slideBg']")  # 定位元素
        # s = element.get_attribute("style")  # 获取元素值
        # p = 'background-image: url((.*)\);'  # 正则表达式 \\. 表示转义
        # img1 = re.findall(p, s, re.S)[0]  # re.S表示点号匹配任意字符，包括换行符
        # print("滑块验证图片下载路径:", img1)  # 打印结果
        #

        bg_img_url = driver.find_element(By.XPATH, "//img[@class='yidun_bg-img']").get_attribute('src')  # 定位元素
        print(bg_img_url)
        spider_img_url = driver.find_element(By.XPATH, "//img[@class='yidun_jigsaw']").get_attribute('src')  # 定位元素
        print(spider_img_url)

        # img_url为图片链接,
        # file_name为文件储存路径及文件名
        file_name = 'bgimg.jpg'
        file_name2 = 'jigsaw.jpg'

        res = requests.get(bg_img_url)
        with open(file_name, 'wb') as f:
            f.write(res.content)

        res = requests.get(spider_img_url)
        with open(file_name2, 'wb') as f:
            f.write(res.content)

        # 分析
        # 等待验证码图片,并截图保存
        # WebDriverWait(driver, 10).until(lambda x: x.find_element_by_class("yidun_panel-placeholder")).screenshot('intersection.png')
        driver.find_element(By.XPATH, "//div[@class='yidun_panel-placeholder']").screenshot('intersection.png')
        #
        # path = file_name
        path = 'intersection.png'
        image = cv2.imread(path)
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)  # Converting BGR to RGB
        plt.imshow(image)
        plt.show()

        canny = cv2.Canny(image, 100, 500)
        plt.imshow(canny)
        plt.show()

        image, contours, hierarchy = cv2.findContours(canny, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
        dx, dy = 0, 0
        for i, contour in enumerate(contours):
            x, y, w, h = cv2.boundingRect(contour)
            if (w > 50) and (h > 50):
                dx = x
                dy = y
            cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)

        plt.imshow(image)
        plt.show()

        time.sleep(100)

        driver.quit()
        pass

    def parse(self, response):
        """
        :param response:
        :return:
        """

        pass
